﻿using Freshbox2._0.BLL;
using Freshbox2._0.MODEL;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
using System.Text;
using Freshbox2._0.COMMON;


namespace Freshbox2._0.UI.Controllers
{
    [Freshbox2._0.UI.Filters.CheckLogin(IsCheck = false)]
    public class LoginController : BaseController<admin>
    {
        //登录验证
        AdminBll adminBll = new AdminBll();
        
        /// <summary>
        /// 用户登陆
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
       
        public  ActionResult Index(Freshbox2._0.BLL.AdminBll.LoginModel model)
        {
            //https://www.cnblogs.com/M-LittleBird/p/5855967.html  传递参数  获取参数

            //var name=Request.QueryString["name"];
            //var password = Request.QueryString["password"];
            //var s= name.ToString() + "  " + password.ToString();

            //修改表 结构    MD5加密 注意修改

            if (string.IsNullOrEmpty(model.code))   
            {
                Response.Write("<script type='text/javascript'>alert('用户名不能为空');</script>");
            }
            if (string.IsNullOrEmpty(model.pwd))
            {
                Response.Write("<script type='text/javascript'>alert('密码不能为空');</script>");

            }
            if (string.IsNullOrEmpty(model.yanZheng))
            {
                Response.Write("<script type='text/javascript'>alert('验证码不能为空');</script>");

            }
            admin u = adminBll.GetUserByNameAndPwd(model);

            if (u != null && model.yanZheng == Session["CheckCode"].ToString())
            {
                Session["CurrentUer"] = u;
                return RedirectToAction("Index", "Home");
            }
            else
            {
                Response.Write("<script type='text/javascript'>alert('用户名或密码错误');</script>");
            }
            return View();
        }


        public ActionResult GetImgCode()
        {
            string checkCode = CodeImage.GetCode(4);//生成随机数  
            Session["CheckCode"] = checkCode;
            MemoryStream ms = CodeImage.GetImage(checkCode);//创建图片
            return File(ms.ToArray(), "image/gif");
        }

        //MD5加密方法  32位加密  接触过net
        public static string MD5Encrypt32(string password)
        {
            string cl = password;
            string pwd = "";
            MD5 md5 = MD5.Create(); //实例化一个md5对像
            // 加密后是一个字节类型的数组，这里要注意编码UTF8/Unicode等的选择　
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
            // 通过使用循环，将字节类型的数组转换为字符串，此字符串是常规字符格式化所得
            for (int i = 0; i < s.Length; i++)
            {
                // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符 
                pwd = pwd + s[i].ToString("X");
            }
            return pwd;
        }

    }
}
